import settings from '../util/settings/settings.js';
import webviews from '../webviews.js';
import ProcessSpawner from '../util/process.js';

import Bitwarden from './bitwarden.js';
import OnePassword from './onePassword.js';
import Keychain from './keychain.js';
const ipc = window.require('electron').ipcRenderer;
const PasswordManagers = {
  // List of supported password managers. Each password manager is expected to
  // have getSuggestions(domain) method that returns a Promise with credentials
  // suggestions matching given domain name.
  managers: [new Bitwarden(), new OnePassword(), new Keychain()],
  // Returns an active password manager, which is the one that is selected in app's
  // settings.
  getActivePasswordManager: () => {
    if (PasswordManagers.managers.length === 0) {
      return null;
    }
    return PasswordManagers.managers.find(
      (mgr) => mgr.name === 'Built-in password manager'
    );
    // const managerSetting = settings.get('passwordManager');
    // if (managerSetting == null) {
    //   return PasswordManagers.managers.find(
    //     mgr => mgr.name === 'Built-in password manager'
    //   );
    // }

    // return PasswordManagers.managers.find(
    //   mgr => mgr.name === managerSetting.name
    // );
  },
  getConfiguredPasswordManager: async () => {
    const manager = PasswordManagers.getActivePasswordManager();
    if (!manager) {
      return null;
    }

    // const configured = await manager.checkIfConfigured();
    // if (!configured) {
    //   return null;
    // }

    return manager;
  },
  // Shows a prompt dialog for password store's master password.
  promptForMasterPassword: async (manager) => {
    return new Promise((resolve, reject) => {
      const { password } = ipc.sendSync('prompt', {
        text: l('passwordManagerUnlock').replace('%p', manager.name),
        values: [
          { placeholder: l('password'), id: 'password', type: 'password' },
        ],
        ok: l('dialogConfirmButton'),
        cancel: l('dialogSkipButton'),
        height: 160,
      });
      if (password === null || password === '') {
        reject();
      } else {
        resolve(password);
      }
    });
  },
  unlock: async (manager) => {
    let success = false;
    while (!success) {
      let password;
      try {
        password = await PasswordManagers.promptForMasterPassword(manager);
      } catch (e) {
        // dialog was canceled
        break;
      }
      try {
        success = await manager.unlockStore(password);
      } catch (e) {
        // incorrect password, prompt again
      }
    }
    return success;
  },
  // Binds IPC events.
};

export default PasswordManagers;
